#include "message_history_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"

#include "call_center_cache.h"

namespace imserver {
namespace fcgi {

UserProfile & GetUserProfile(int64_t qid, std::map<int64_t, UserProfile> & cache) {
  if (cache.find(qid) != cache.end()) {
    return cache.find(qid)->second;
  }
  int ret = UserProfileAdapter::Instance().Get(qid, &cache[qid], 3);
  if (ret == 0) {
    if (qid == 127646892) {
      cache.find(qid)->second.__set_shop_name("穆的小店");
      cache.find(qid)->second.__set_shop_url("http://bang.360.cn/");
    }
    return cache.find(qid)->second;
  }
  cache.erase(qid);

  static UserProfile up;
  return up;
}

bool MessageHistoryRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }
  ParseUserIdentity();

  int64_t peer_id = 0;
  try {
    peer_id = boost::lexical_cast<int64_t>(GetQuery("peer"));
  } catch (boost::bad_lexical_cast&) {}

  int64_t page = 0;
  try {
    page = boost::lexical_cast<int64_t>(GetQuery("pn"));
  } catch (boost::bad_lexical_cast&) {}

  const int kCountPerPage = 10;

  MessageResult res;
  if (effective_id() > 0 && peer_id > 0) {
    MessageHistoryAdapter::Instance().GetMessages(effective_id(), peer_id, page * kCountPerPage, kCountPerPage, &res, 3);
    LOG_INFO("message history get, offset=" << page * kCountPerPage << " uid=" 
              << effective_id() << " peer=" << peer_id << " size=" << res.results.size());
  } else {
    LOG_WARN("message history bad param uid=" << effective_id() << " peer=" << peer_id);
  }
  
  std::stringstream rsp_header;
  rsp_header << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  std::stringstream rsp_body;
  std::string callback = ParseCallback();

  if (!callback.empty()) {
    // 开头空格是 IE bug fix
    rsp_body << ' ' << callback << "(";
  }

  // TODO : 使用ctemplate渲染 
  rsp_body << "{\"total\":" << (res.count < 100 ? res.count : -1)
           << ",\"count_per_page\":" << kCountPerPage
           << ",\"offset\":" << page * kCountPerPage
           << ",\"peer_id\":" << peer_id << ',';

  UserProfile peer_profile;
  if (peer_id > 0 && peer_id < IM_TEMP_ID_BASE) {
    UserProfileAdapter::Instance().Get(peer_id, &peer_profile, 3);
    if (peer_profile.qid > 0) {
      rsp_body << "\"peer_username\":\"" << base::JsonEscape(peer_profile.username)
             << "\",\"peer_head_pic\":\"" << base::JsonEscape(peer_profile.head_pic)
             << "\",";
    }
  }
  if (peer_profile.qid <= 0) {
    rsp_body << "\"peer_username\":\"" << GetDefaultUsername(peer_id)
             << "\",\"peer_head_pic\":\"" << base::JsonEscape(kDefaultHeadPic)
             << "\",";
  }

  std::map<int64_t, UserProfile> user_profile_cache;

  rsp_body << "\"msg_list\":[";
  bool is_waiter = CallCenterCache::Instance().IsWaiter(effective_id());
  for (size_t i = 0; i < res.results.size(); ++i) {
    int message_type = MessageType(res.results[i]);
    if (MSG_TYPE_BANG_ORDER == message_type && effective_id() == res.results[i].sender) {
      //当消息类型是同城帮订单且当前用户是该消息的发送者时忽略消息。
      continue;
    }
    if (i > 0) {
      rsp_body << ',';
    }
    rsp_body << "{\"sender\":" << res.results[i].sender
             << ",\"receiver\":" << res.results[i].receiver
             << ",\"mtype\":" << message_type
             << ",\"timestamp\":" << res.results[i].timestamp
             << ",\"message\":\"" << base::JsonEscape(res.results[i].body);
  //if (is_waiter && res.results[i].__isset.via_shop) {
  //  UserProfile & up = GetUserProfile(res.results[i].via_shop, user_profile_cache);
  //  rsp_body << "\", \"via_shop\":\"" << res.results[i].via_shop;
  //  if (up.__isset.shop_name) {
  //    rsp_body << "\", \"via_shop_name\":\"" << base::JsonEscape(up.shop_name);
  //  }
  //  if (up.__isset.shop_url) {
  //    rsp_body << "\", \"via_shop_url\":\"" << up.shop_url;
  //  }
  //}

    if (is_waiter && res.results[i].__isset.via_shop) {
      rsp_body << "\", \"via_shop\":\"" << res.results[i].via_shop;
      if (res.results[i].__isset.via_shop_name) {
        rsp_body << "\", \"via_shop_name\":\"" << base::JsonEscape(res.results[i].via_shop_name);
      }
      if (res.results[i].__isset.via_shop_url) {
        rsp_body << "\", \"via_shop_url\":\"" << res.results[i].via_shop_url;
      }
    }
    rsp_body << "\"}";
  }
  rsp_body << "]}";

  if (!callback.empty()) {
    rsp_body << ")";
  }

  LOG_DEBUG("MessageHistoryRequest rsp=" << rsp_body.str());

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);
  return true;
}

}
}


